﻿using System.Windows;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        public static void SwitchLineAndColumn()
        {
            if (Globals.selectedEditor == null) return;
            if (Globals.selectedEditor.SelectedExpression == null) return;

            if ((Globals.selectedEditor.SelectedExpression is Expressions.Grid) == false)
            {
                MessageBox.Show("只有网格式才支持“行列转置”操作！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            LunarPresentation.Expressions.Grid grid
                = Globals.selectedEditor.SelectedExpression as Expressions.Grid;

            RunSwitchLineAndColumn(grid);

            ModifingItem mi = new ModifingItem();
            Action action = new Action(grid.ExID, grid.ParentPanel.BasePanel.Children.IndexOf(grid),
                grid.GetType().Name, "SwitchLineAndColumn", null, null);
            mi.Add(action);
            grid.Editor.Do(mi);
        }

        public static void RunSwitchLineAndColumn(LunarPresentation.Expressions.Grid grid)
        {
            // 此功能不支持有合并单元格的情况。
            foreach (Expressions.SubPanel sPanel in grid.SubPanels)
            {
                Expressions.GridPanel gp = sPanel as Expressions.GridPanel;

                if (gp != null &&
                    gp.MergeStanding != Expressions.GridPanel.Standing.Normal)
                {
                    MessageBox.Show("网格式中有合并单元格时，“行列转置”这一功能无效！",
                        Globals.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }

            int lc = grid.LinesCount;
            int cc = grid.ColumnsCount;

            grid.ColumnsCount = lc;
            grid.LinesCount = cc;

            if (grid.SubPanels.Count >= 1)
            {
                foreach (Expressions.SubPanel sPanel in grid.SubPanels)
                {
                    Expressions.GridPanel gp = sPanel as Expressions.GridPanel;

                    if (gp != null)
                    {
                        int tmp = gp.GridX;
                        gp.GridX = gp.GridY;
                        gp.GridY = tmp;
                    }
                }

                grid.Editor.IsModified = true;
            }
        }
    }
}
